<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="js/vue.min.js"></script>
</head>
<body>
<form>
    姓名:<input v-model="user.name"><span>{{result.nameMsg}}</span><br>
    密码:<input v-model="user.pwd"><span>{{result.pwdMsg}}</span><br>
    年龄:<input v-model="user.age"><span>{{result.ageMsg}}</span><br>
    邮箱:<input v-model="user.email"><span>{{result.emailMsg}}</span><br>
    电话:<input v-model="user.phone"><span>{{result.phoneMsg}}</span><br>
    文件上传:<input type="file" id="fl" name="filename" @change="upload">
            <img :src="user.head" alt="没有头像" style="width: 100px; height: 150px"><br>
    <button @click.prevent="reg">注册</button>
</form>

<script>
    var v = new Vue({
        el : "form",
        data : {
            user : {},
            result : {}
        },
        methods:{
            reg(){
                axios.post("user/reg", this.user).then(res=>{
                this.result = {}
                // res.data => [{field:?, defaultMessage:?}, ...]
                this.result.nameMsg = this.castMsg(res.data.data, "name");
                this.result.pwdMsg = this.castMsg(res.data.data, "pwd");
                this.result.ageMsg = this.castMsg(res.data.data, "age");
                this.result.emailMsg = this.castMsg(res.data.data, "email");
                this.result.phoneMsg = this.castMsg(res.data.data, "phone");
                this.$forceUpdate();  // vue 强制渲染
                });
            },
            castMsg(data, filedName){
                return data.filter( o => o.field == filedName ) // 过滤
                    .map( o => {return o.defaultMessage}) // 转换
                    .join( ", ");
            },
            upload(){
                let fd = new FormData();  // 文件上传对象
                if (fl.files.length == 0){
                    alert("请选择要上传的文件！");
                    return;
                }
                fd.append("filename", fl.files[0]);
                axios.post("user/upload", fd).then(res=>{
                    console.log(123)
                    // 去掉第一个 /
                    this.user.head = res.data.data.substring(1);
                    // 强制刷新
                    v.$forceUpdate();
                })
            }
        }
    })
</script>
<style>
    span{
        color: red;
    }
</style>
</body>
</html>